package com.ruoyi.project.system.controller;

import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.project.system.domain.PerQueryList;
import com.ruoyi.project.system.domain.ResTable;
import com.ruoyi.project.system.domain.dto.ReservationSubmitDTO;
import com.ruoyi.project.system.service.PerQueryListService;
import com.ruoyi.project.system.service.ResTableService;
import com.ruoyi.project.system.service.ITempWeekDailyService; // 新增：导入值班表Service
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; // 新增：日志（便于排查问题）
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * 预约控制器（集成：skipQuery问卷控制 + 值班名额扣减）
 */
@RestController
@RequestMapping("/reservation")
public class ReservationController {

    private static final Logger logger = LoggerFactory.getLogger(ReservationController.class); // 新增：日志实例

    @Resource
    private PerQueryListService perQueryListService;
    @Resource
    private ResTableService resTableService;
    @Resource
    private ITempWeekDailyService tempWeekDailyService; // 新增：注入值班表Service

    @PostMapping("/submit")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult submitReservation(@RequestBody ReservationSubmitDTO submitDTO) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            // 1. 基础参数校验（新增：校验值班表扣减必要字段 + skipQuery）
            if (submitDTO == null) {
                return AjaxResult.error("提交数据不能为空");
            }
            if (submitDTO.getDoctorId() == null || submitDTO.getAppointmentDate() == null) {
                return AjaxResult.error("医生ID或预约日期不能为空");
            }
            logger.info("接收预约请求：skipQuery={}，doctorId={}，appointmentDate={}",
                    submitDTO.getSkipQuery(), submitDTO.getDoctorId(), submitDTO.getAppointmentDate());

            // 2. 登录态校验（原有逻辑不变）
            Long userId = SecurityUtils.getUserId();
            if (userId == null || userId <= 0) {
                return AjaxResult.error("用户未登录，请重新登录");
            }

            // 3. 时间格式解析（原有逻辑不变）
            Date appointmentDatetime = null;
            try {
                appointmentDatetime = sdf.parse(submitDTO.getDatetime().trim());
            } catch (ParseException e) {
                logger.error("时间格式错误", e);
                return AjaxResult.error("预约时间格式错误，请传入 yyyy-MM-dd HH:mm:ss 格式");
            }

            // 新增：检查重复预约
            List<ResTable> existingReservations = resTableService.selectExistingReservation(
                    submitDTO.getDoctorId(),
                    submitDTO.getDepartmentId(),
                    appointmentDatetime
            );

            if (!existingReservations.isEmpty()) {
                logger.warn("检测到重复预约：doctorId={}, departmentId={}, datetime={}",
                        submitDTO.getDoctorId(), submitDTO.getDepartmentId(), appointmentDatetime);
                return AjaxResult.error("已有该科室的预约，请先取消后再预约");
            }

            // 4. 构建预约主表（新增：根据 skipQuery 赋值 queryIs）
            ResTable resTable = new ResTable();
            resTable.setUserId(userId);
            resTable.setName(submitDTO.getName().trim());
            resTable.setIdentity(submitDTO.getIdentity().trim());
            resTable.setPhone(submitDTO.getPhone().trim());
            resTable.setDepartmentId(submitDTO.getDepartmentId());
            resTable.setDoctor(submitDTO.getDoctor().trim());
            resTable.setDatetime(appointmentDatetime);
            resTable.setDoctorId(submitDTO.getDoctorId()); 
            resTable.setCreateTime(new Date());
            String resId = "RES_" + userId + "_" + System.currentTimeMillis();
            resTable.setResId(resId);

            // 核心新增1：根据 skipQuery 控制 queryIs（0=跳过问卷，1=填写问卷）
            boolean isSkipQuery = "true".equals(submitDTO.getSkipQuery());
            resTable.setQueryIs(isSkipQuery ? 0 : 1); // 给预约表赋值问卷状态
            logger.info("预约单号{}：skipQuery={}，queryIs={}", resId, submitDTO.getSkipQuery(), resTable.getQueryIs());

            // 5. 保存预约主表（原有逻辑不变）
            boolean resSaveSuccess = resTableService.saveResTable(resTable);
            if (!resSaveSuccess) {
                logger.error("预约表保存失败，resId={}", resId);
                return AjaxResult.error("预约信息保存失败，请重试");
            }

            // 核心新增2：根据 skipQuery 控制是否插入问卷表
            if (!isSkipQuery) { // 未跳过问卷（填写了）→ 插入问卷表
                PerQueryList perQueryList = new PerQueryList();
                perQueryList.setUserId(userId);
                perQueryList.setResId(resId);
                perQueryList.setAnswer1(submitDTO.getAnswer1());
                perQueryList.setAnswer2(submitDTO.getAnswer2());
                perQueryList.setAnswer3(submitDTO.getAnswer3());
                perQueryList.setAnswer4(submitDTO.getAnswer4());
                perQueryList.setAnswer5(submitDTO.getAnswer5());
                perQueryList.setAnswer6(submitDTO.getAnswer6());
                perQueryList.setAnswer7(submitDTO.getAnswer7());
                perQueryList.setAnswer8(submitDTO.getAnswer8());
                perQueryList.setAnswer9(submitDTO.getAnswer9());
                perQueryList.setAnswer10(submitDTO.getAnswer10());
                perQueryList.setCreateTime(new Date());

                boolean querySaveSuccess = perQueryListService.savePerQueryList(perQueryList);
                if (!querySaveSuccess) {
                    logger.error("问卷表保存失败，resId={}", resId);
                    throw new RuntimeException("问卷信息保存失败");
                }
                logger.info("问卷表保存成功，resId={}", resId);
            } else { // 跳过问卷 → 不插入问卷表
                logger.info("已跳过问卷，不插入问卷表，resId={}", resId);
            }

            // 核心新增3：预约成功后，扣减值班表剩余名额
            boolean decreaseSuccess = tempWeekDailyService.decreaseRemaining(
                    submitDTO.getDoctorId(), // 医生ID（DTO新增字段）
                    submitDTO.getAppointmentDate() // 预约日期（DTO新增字段，YYYY-MM-DD）
            );
            if (!decreaseSuccess) {
                logger.error("值班名额扣减失败，doctorId={}，date={}", submitDTO.getDoctorId(), submitDTO.getAppointmentDate());
                throw new RuntimeException("医生当天无值班记录或名额已用尽");
            }
            logger.info("值班名额扣减成功，doctorId={}，date={}", submitDTO.getDoctorId(), submitDTO.getAppointmentDate());

            // 6. 返回结果（原有逻辑不变）
            return AjaxResult.success("预约提交成功", resId);

        } catch (Exception e) {
            logger.error("服务器异常", e);
            return AjaxResult.error("服务器异常：" + e.getMessage());
        }
    }
}